package com.kaifamiao.thread.d0926;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;

public class ConnectionPool {

    private static final int default_size = 5;

    private LinkedList<Connection> list = new LinkedList<>();

    private int size;

    public ConnectionPool(){
        initConnection();
    }

    public ConnectionPool(int size){
        if (size <= 0){
            throw new IllegalArgumentException("参数错误");
        }
        this.size = size;
        initConnection();
    }

    private void initConnection(){
        int s = default_size;
        if (size != 0){
            s = size;
        }

        for (int i = 0 ; i < s; i ++){
            try {
                list.add(DriverManager.getConnection(""));
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public Connection get(){
        return list.size() > 0? list.remove() : null;
    }


    public void close(Connection connection){
        list.add(connection);
    }

}
